from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib import parse
import subprocess
import time

#####
# python3 -u publish_server.py > /var/log/update.log 2>&1 &:
# refers:


def update_module(module_name, version):
    if module_name.find('web') > 0:
        command = "/bin/bash /opt/update-web-app.sh {} {}".format(module_name, version)
    else:
        command = "/bin/bash /opt/update-java-app.sh {} {}".format(module_name, version)
    return exec_command(command)


class ShellHandler(BaseHTTPRequestHandler):
    def do_GET(self):

        # ParseResult(scheme='', netloc='', path='/a/v/b', params='', query='q=1', fragment='')
        parsed_result = parse.urlparse(self.path)
        params = parsed_result.query
        url_path = parsed_result.path
        if not params:
            self.response(404, "not found path: {}".format(url_path))
        else:
            param_dict = {}
            for param_pair in params.split('&'):
                key, value = param_pair.split('=')
                param_dict[key] = value

            module_name = param_dict.get('module')
            localtime = time.localtime(time.time())
            strftime = time.strftime("%Y%m%d%H%M%S", localtime)
            version = strftime
            if not module_name:
                error_msg = "not found param: module_name"
                print(error_msg)
                self.response(500, error_msg)
                return
            if url_path.find('/publish') == 0:
                code, msg_bytes = update_module(module_name, version)
                self.return_shell_result(code, msg_bytes)
            else:
                self.response(404, "not found path: {}".format(url_path))

    def response(self, status, msg):
        self.send_response(status)
        self.send_header('Content-Type',
                         'text/plain; charset=utf-8')
        self.end_headers()
        self.wfile.write(msg.encode('utf-8'))

    def return_shell_result(self, code, msg_bytes):
        msg = str(msg_bytes, encoding='utf-8')
        if code != 0:
            self.response(500, msg)
        else:
            self.response(200, msg)


def exec_command(command):
    result = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output = result.communicate()[0]
    return result.returncode, output


def run(server_class=HTTPServer, handler_class=ShellHandler):
    server_address = ('', 18100)
    httpd = server_class(server_address, handler_class)
    print("starting publish service...")
    httpd.serve_forever()


if __name__ == '__main__':
    run()
